<?php

namespace App\Models\WorkOrder;

use App\Enums\OpenShop\InvestmentPromotion\ShopManualEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\BaseModel;
use App\Models\Common\ResourcesModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopShopManual;
use App\Models\Traits\KfUid;
use App\Remote\Rms\RmsUserRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Collection;

class WorkOrderApplyContentModel extends BaseModel
{
    use KfUid;

    protected $table = 'work_order_apply_content';

    protected $fillable = [
        'workOrderNo',
        'content',
        'createdByUid',
        'updatedByUid',
        'createdAt',
        'updatedAt',
    ];

    const YES           = 1;
    const NO            = 2;
    const YES_OR_NO_MAP = [
        self::YES => "是",
        self::NO  => "否"
    ];


    const COLLECTION_TYPE_PUBLIC  = 1;
    const COLLECTION_TYPE_PRIVATE = 2;

    //收款类型
    const COLLECTION_TYPE_MAP = [
        self::COLLECTION_TYPE_PUBLIC  => "对公",
        self::COLLECTION_TYPE_PRIVATE => "对私",
    ];

    const COLLECTION_EQ_BANK_CARD_YES = 1;
    const COLLECTION_EQ_BANK_CARD_NO  = 2;

    //收款人与银行卡持卡人是否一致
    const COLLECTION_EQ_BANK_CARD_MAP = [
        self::COLLECTION_EQ_BANK_CARD_YES => "是",
        self::COLLECTION_EQ_BANK_CARD_NO  => "否",
    ];

    const STORE_IN_FOOD_CITY_YES = 1;
    const STORE_IN_FOOD_CITY_NO  = 2;
    const STORE_IN_FOOD_CITY_MAP = [
        self::STORE_IN_FOOD_CITY_YES => "是",
        self::STORE_IN_FOOD_CITY_NO  => "否",
    ];


    const CASHIER_SYSTEM_KF    = 1;
    const CASHIER_SYSTEM_MT    = 2;
    const CASHIER_SYSTEM_THIRD = 3;
    const CASHIER_SYSTEM_MAP   = [
        self::CASHIER_SYSTEM_KF    => "夸父收银",
        self::CASHIER_SYSTEM_MT    => "美团收银",
        self::CASHIER_SYSTEM_THIRD => "其他三方收银",
    ];

    //手持身份证默认人像图片
    const DEFAULT_PERSON_IDENTITY_CARD_HAND_IMG = 'https://file.51kuafu.com/c1/9e/a61f58ba971ead79d7adaae40add5eab2208a031d049c9f5212d082c31f5.png';
    //手持身份证默认国徽图片
    const DEFAULT_PERSON_IDENTITY_CARD_HAND_BACK_IMG = 'https://file.51kuafu.com/6a/8d/7c1e32a6f679c85d9db2c73251b922040cbc36d8dd483c35c5e8e1e38850.png';
    //身份证默认提示文案
    const DEFAULT_PERSON_IDENTITY_CARD_DESC_LIST = [
        "四角完整 照片清晰 三证合一",
        "须使用二代身份证,个人工商户须提供经营者身份证,企业须提供法定代表人身份证",
        "请提供有效期范围内的的证件,证件需漏出四角,请勿遮挡或模糊,保持信息清晰可见"
    ];

    public static ?array                    $tempApplyContent         = null;
    public static ?OpenShopShopManual       $openShopShopManual       = null;
    public static ?OpenShopMainProcessModel $openShopMainProcessModel = null;

    /**
     * 创建或获取申请内容
     *
     * @param string $workOrderNo
     * @param int $uid
     * @param int $shopId
     * @return Builder|Model
     * @throws GuzzleException
     */
    public static function getOrCreateFunctionOpenApplyContent(
        string $workOrderNo,
        int $uid,
        int $shopId
    ) {
        return self::customFirstOrCreate(
            [
                "workOrderNo" => $workOrderNo,
            ],
            function () use ($shopId, $uid, &$shopShopManual) {
                if (empty(self::$tempApplyContent)) {
                    $shopInfo = (object)current((new RmsShopApi())->getShopByIds([$shopId])["data"]["shopList"]);

                    self::$openShopShopManual = (self::$openShopShopManual ?? OpenShopShopManual::query()
                                                                                                ->where("shopCode",
                                                                                                    $shopInfo->shopCode)
                                                                                                ->where("type",
                                                                                                    ShopManualEnum::TYPE_CERTIFICATE)
                                                                                                ->first());

                    self::$openShopMainProcessModel = (self::$openShopMainProcessModel ?? OpenShopMainProcessModel::query()
                                                                                                                  ->where("shopId",
                                                                                                                      $shopId)
                                                                                                                  ->where("childLocationOrder",
                                                                                                                      0)
                                                                                                                  ->with([
                                                                                                                      "signOrderRel" => function (
                                                                                                                          $query
                                                                                                                      ) {
                                                                                                                          $query->with(["checkAcceptRel"]);
                                                                                                                      }
                                                                                                                  ])
                                                                                                                  ->first());

                    $shopSupervisorName = $shopSupervisorMobile = "";

                    if (self::$openShopMainProcessModel && self::$openShopMainProcessModel->signOrderRel && self::$openShopMainProcessModel->signOrderRel->checkAcceptRel) {
                        $shopSupervisorName = self::$openShopMainProcessModel->signOrderRel->checkAcceptRel->managerName ?? "";
                        $shopSupervisorUid  = self::$openShopMainProcessModel->signOrderRel->checkAcceptRel->managerId ?? 0;
                        if ($shopSupervisorUid > 0) {
                            $userInfo             = RmsUserRemote::getRmsUserByIds([$shopSupervisorUid]);
                            $shopSupervisorMobile = collect($userInfo)->keyBy("id")
                                                                      ->get($shopSupervisorUid, [])["mobile"] ?? "";
                        }
                    }

                    self::$tempApplyContent = [
                        "createdByUid" => $uid,
                        "content"      => json_encode([
                            "mobile"                     => $shopInfo->shopMobile,
                            "address"                    => [
                                "cityCode"      => $shopInfo->city,
                                "districtCode"  => $shopInfo->district,
                                "provinceCode"  => $shopInfo->province,
                                "addressPrefix" => $shopInfo->addressPrefix,
                            ],
                            "shopCode"                   => (string)$shopInfo->shopCode,
                            "shopName"                   => $shopInfo->name,
                            "detailAddress"              => $shopInfo->address,
                            "businessTime"               => ["startTime" => "10:00", "endTime" => "22:00"],
                            "takeDeliveryDetailAddress"  => "{$shopInfo->addressPrefix} {$shopInfo->address}",
                            "shopInFoodCity"             => WorkOrderApplyContentModel::STORE_IN_FOOD_CITY_NO,
                            "initAuthorizationLetterImg" => (bool)self::$openShopShopManual,
                            "shopSupervisorName"         => $shopSupervisorName,
                            "shopSupervisorMobile"       => $shopSupervisorMobile,
                            "cashierSystem"              => self::CASHIER_SYSTEM_KF
                        ], JSON_UNESCAPED_UNICODE),
                        "updatedAt"    => time(),
                        "createdAt"    => time()
                    ];
                }
                return self::$tempApplyContent;
            },
            function (WorkOrderApplyContentModel $applyContentModel) {
                if (self::$openShopShopManual) {
                    ResourcesModel::moduleBusinessSingleResourcesUpdate(
                        ResourcesModel::MODULE_TYPE_WORK_ORDER,
                        ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN,
                        "authorizationLetterImg",
                        $applyContentModel->id,
                        (array)self::$openShopShopManual->url,
                        in_array("authorizationLetterImg", ResourcesModel::$privateResourcesFields) ? 0 : 1
                    );
                }
            }
        );
    }


    /**
     * @return HasOne
     */
    public function applyMainRel(): HasOne
    {
        return $this->hasOne(WorkOrderApplyMainModel::class, "workOrderNo", "workOrderNo");
    }

    /**
     * 获取表单content
     *
     * @param WorkOrderApplyContentModel $applyContentModel
     * @param array $mergeData
     * @return Collection
     */
    public static function getContent(WorkOrderApplyContentModel $applyContentModel, array $mergeData = []): Collection
    {
        return collect(json_decode($applyContentModel->content, JSON_UNESCAPED_UNICODE))->merge($mergeData);
    }


    /**
     * 更新表单数据
     *
     * @param WorkOrderApplyContentModel $applyContentModel
     * @param array $params
     */
    public static function updateContent(WorkOrderApplyContentModel $applyContentModel, array $params)
    {
        if (!empty($params)) {
            $applyContentModel->update(
                [
                    "content"   => WorkOrderApplyContentModel::getContent($applyContentModel, $params)
                                                             ->toJson(JSON_UNESCAPED_UNICODE),
                    "updatedAt" => time()
                ]
            );
        }
    }

    /**
     * 通过工单号查询信息
     * @param string $workOrderNo
     * @return Builder|Model|object|null
     */
    public static function getApplyContentByWorkOrderNo(string $workOrderNo)
    {
        return self::query()
            ->where('workOrderNo', $workOrderNo)
            ->with('resourceWorkOrderNoImgRel')
            ->select('id', 'workOrderNo', 'content')
            ->first();
    }

    public function resourceWorkOrderNoImgRel(): HasMany
    {
        return $this->hasMany(ResourcesModel::class, 'businessId')
            ->where('module', ResourcesModel::MODULE_TYPE_WORK_ORDER)
            ->where('business', ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN)
            ->whereIn(
                'name', [
                'authorizationLetterImg', 'legalPersonIdentityCardFront', 'legalPersonIdentityCardBack',
                'businessLicenseImg', 'companyBankCardImg', 'legalPersonBankCardFrontImg',
                'payeeIdentityCardFront', 'payeeIdentityCardBack', 'merchantRelationshipImg',
            ]
            );
    }
}
